<?php

namespace app\base\command;


use app\base\model\RedianData;
use app\base\model\RedianTask;
use app\base\service\TaskService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
/**
 * 小甲鱼生成的视频下载到服务器任务
 * Class SmsNum
 * @package app\common\command
 */
class XiaojiayuVideoDownload extends Command
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xbase:XiaojiayuVideoDownload');
        $this->setDescription('XiaojiayuVideoDownload');
    }

    protected function execute(Input $input, Output $output)
    {
        $data = $this->app->db->name("redian_data")
            ->where(['video_status'=>3,'is_download_video_serve'=>0])
            ->whereLike("video_url","%yc-digital-human%")
            ->select()->toArray();
        $videoDir = $this->app->getRootPath() . "public/upload/video_create/";
        if (!is_dir($videoDir)) {
            mkdir($videoDir, 0755, true);
        }
        $num = 1;
        $output->info("总共需要处理的数据为: ".count($data)."条");
        foreach ($data as $item){
            //$video_url = $other_data['coverUrl'];
            $output->info("开始处理第{$num}条数据");
            $video_url = $item['video_url'];
            // 提取文件后缀名称（核心逻辑）
            $extension = $this->extractExtensionFromUrl($video_url);

            // 使用后缀名构建完整保存路径
            $filename = md5($item['id']) . '.' . ($extension ?: 'mp4'); // 默认mp4
            $savePath = $videoDir . '/' . $filename;

            // 下载图片并更新数据库
            try {
                $this->downloadVideo($video_url, $savePath);
                $host_pic_url =  "http://dev.blueant.pro/upload/video_create/{$filename}";
                $this->app->db->name("redian_data")
                    ->where('id', $item['id'])
                    ->update([
                        'is_download_video_serve' => 1,
                        'video_url' => $host_pic_url
                    ]);

                $output->info("下载成功: {$item['id']} URL: {$host_pic_url}");

            } catch (\Exception $e) {
                $this->app->db->name("redian_data")
                    ->where('id', $item['id'])
                    ->update([
                        'is_download_video_serve' => 1,
                    ]);
                $output->info("下载失败: {$item['id']} - {$e->getMessage()}");
            }
            $num++;
        }
        $this->setQueueSuccess("任务完成");

    }

    /**
     * 下载图片到本地
     */
    private function downloadVideo(string $url, string $savePath): void
    {
        // 使用cURL流式下载
        $ch = curl_init($url);
        $fp = fopen($savePath, 'wb');

        curl_setopt_array($ch, [
            CURLOPT_FILE => $fp,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 3000, // 5分钟超时
            CURLOPT_USERAGENT => 'Mozilla/5.0',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);

        if (!curl_exec($ch)) {
            fclose($fp);
            unlink($savePath); // 删除可能的部分文件
            throw new \Exception("视频下载失败: " . curl_error($ch));
        }

        fclose($fp);
        curl_close($ch);

        // 验证文件完整性
        if (!file_exists($savePath) || filesize($savePath) === 0) {
            throw new \Exception("视频保存失败，文件为空");
        }
    }


    /**
     * 从URL解析文件后缀名
     */
    private function extractExtensionFromUrl(string $url): string
    {
        // 方法1：直接从URL路径解析（高效）
        $path = parse_url($url, PHP_URL_PATH);
        if ($path && ($ext = pathinfo($path, PATHINFO_EXTENSION))) {
            return strtolower($ext);
        }

        // 方法2：正则匹配（更灵活）
        if (preg_match('/\.([a-z0-9]{2,5})(?:[\?#]|$)/i', $url, $matches)) {
            return strtolower($matches[1]);
        }

        // 方法3：备用方案 - 从文件名部分解析
        $parts = explode('/', $url);
        $filename = end($parts);
        if (($pos = strrpos($filename, '.')) !== false) {
            return strtolower(substr($filename, $pos + 1));
        }

        // 默认返回jpg
        return 'mp4';
    }



}
